package com.totcy.service.impl;

import com.totcy.constant.CommonConstant;
import com.totcy.constant.CommonMethod;
import com.totcy.dao.IUserDao;
import com.totcy.model.User;
import com.totcy.service.IUserService;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

@Service("userService")
public class UserServiceImpl implements IUserService {

    @Resource
    private IUserDao userDao;

    /**
     * 查询用户是否注册
     *
     * @param email
     * @return
     */
    private boolean checkEmailRegister(String email) {
        return this.userDao.checkEmailRegister(email) > 0;
    }

    /**
     * 仅做查询使用
     * @param email
     * @return
     */
    @Override
    public JSONObject selectUser(String email) {
        User user = this.userDao.selectUser(email);

        if (user != null) {
            return CommonMethod.responseResult(CommonConstant.ErrorCode.CODE0, user2JSONObject(user));
        } else {
            return CommonMethod.responseResult(CommonConstant.ErrorCode.CODE1003, null);
        }

/*        return CommonMethod.responseResult(user != null
                        ? CommonConstant.ErrorCode.CODE0
                        : CommonConstant.ErrorCode.CODE1003
                , user != null ? JSONObject.fromObject(user) : new JSONObject());*/
    }

    @Override
    public JSONObject register(User user) {
        if (checkEmailRegister(user.getEmail())) {
            //用户已经注册
            return CommonMethod.responseResult(CommonConstant.ErrorCode.CODE1001, null);
        }
        //注册
        this.userDao.register(user);
        //返回用户信息
        return CommonMethod.responseResult(CommonConstant.ErrorCode.CODE0, user2JSONObject(this.userDao.selectUser(user.getEmail())));
    }

    @Override
    public JSONObject login(HashMap<String, Object> params) {
        //查询用户是否注册
        if (!checkEmailRegister((String) params.get("email"))) {
            //用户不存在
            return CommonMethod.responseResult(CommonConstant.ErrorCode.CODE1003, null);
        }
        //登录
        User user = this.userDao.login(params);
        if (user == null) {
            //密码错误
            return CommonMethod.responseResult(CommonConstant.ErrorCode.CODE1004, null);
        }
        return CommonMethod.responseResult(CommonConstant.ErrorCode.CODE0, user2JSONObject(user));

    }

    /**
     * user 转  JSONObject
     *
     * @param user
     * @return
     */
    private JSONObject user2JSONObject(User user) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", user.getId());
        jsonObject.put("email", user.getEmail());
        jsonObject.put("userName", user.getUserName());
        jsonObject.put("role", user.getRole());
        jsonObject.put("registerTime", user.getRegisterTime().getTime());
        return jsonObject;
    }
}
